package com.yueka.service.Impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yueka.mapper.TeacherInstrumentMapper;
import com.yueka.mapper.TeacherMapper;
import com.yueka.pojo.PageResult;
import com.yueka.pojo.entity.teacher.Teacher;
import com.yueka.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class TeacherServiceImpl implements TeacherService {
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private TeacherInstrumentMapper teacherInstrumentMapper;

    @Override
    @Transactional
    public void insertTeacher(Teacher teacher) {
        teacher.setUpdateTime(LocalDateTime.now());
        teacher.setCreateTime(LocalDateTime.now());
        teacherMapper.insert(teacher);
        Integer id = teacher.getId();
        teacherInstrumentMapper.insert(id, teacher.getInstrumentIds());
    }

    @Override
    public PageResult<Teacher> listTeachers(String keyword, String status, Integer page, Integer pageSize) {
        Page<Teacher> list = teacherMapper.list(new Page<>(page, pageSize), keyword, status);
        list.getRecords().forEach(t -> t.setInstrumentIds(teacherInstrumentMapper.list(t.getId())));
        return new PageResult<>(list.getTotal(), list.getRecords());
    }

    @Override
    @Transactional
    public void updateTeacher(Teacher teacher) {
        teacher.setUpdateTime(LocalDateTime.now());
        teacherMapper.update(teacher);
        Integer[] ids = new Integer[]{teacher.getId()};
        teacherInstrumentMapper.delete(ids);
        teacherInstrumentMapper.insert(teacher.getId(), teacher.getInstrumentIds());
    }

    @Override
    @Transactional
    public void deleteTeacher(Integer[] ids) {
        teacherMapper.delete(ids);
        teacherInstrumentMapper.delete(ids);
    }
}
